-module(dbtest).
-compile(export_all).
-include("usr.hrl").

initdb()->
	mnesia:create_schema([node()]),
	mnesia:start().
inittable()->
	mnesia:create_table(offmsgs,[{attributes,record_info(fields,offmsgs)},{disc_copies,[node()]},{type,ordered_set}]),
	mnesia:create_table(usr,[{attributes,record_info(fields,usr)},{disc_copies,[node()]},{type,ordered_set}]).

addusr(Name,Age,Sex)->
	Usr = #usr{name=Name,age=Age,sex = Sex},
	F = fun() ->
		mnesia:write(Usr)
	end,
	mnesia:transaction(F).
addmsg(From,To,Msg) ->
	Msgs = #offmsgs{from=From,to=To,msg=Msg,date=erlang:now()},
	F = fun() -> mnesia:write(Msgs) end,
	mnesia:transaction(F).
cleanMsg([]) ->
	ok;
cleanMsg([H|T]) ->
	F = fun() ->
		mnesia:dirty_delete_object(offmsgs,H)
	    end,
	mnesia:transaction(F),
	cleanMsg(T).
clearallmsg()->
	Math = #offmsgs{_='_'},
	Guard = [],
	Result = ['$_'],
	F = fun() -> 
		case mnesia:select(offmsgs,[{Math,Guard,Result}]) of
		List ->
			cleanMsg(List);
		_Any ->
			ok
		end
	    end,
	mnesia:transaction(F).	
selectmsg()->
	Math = #offmsgs{_='_'},
	Guard = [],
	Result = ['$_'],
	F = fun() -> 
		mnesia:select(offmsgs,[{Math,Guard,Result}]) 
	    end,
	mnesia:transaction(F).		

selectusr(Name)->
	F = fun()->
		MatchHead = #usr{name=Name,_='_'},
		Guard = [],
		Result = ['$_'],
		mnesia:select(usr,[{MatchHead,Guard,Result}])
	end,
	mnesia:transaction(F).
selectall()->
	MatchHead = #usr{_='_'},
	Guard = [],
	Result = ['$_'],
	F = fun()->mnesia:select(usr,[{MatchHead,Guard,Result}]) end,
	mnesia:transaction(F).
test()->
	initdb(),
	case selectusr("yang") of 
		[H|_T]->
			io_lib:format("~p~n",[H]);
		[] ->
			io:format("Result is empty~n");
		_Any->
			io:format("Can not Find~n")
	end.
